<template>
  <div class="app-container">
    <el-container class="dcs-main-container" >
      <el-aside class="real-aside" width="300px">
        <div style="margin-bottom: 10px"></div>
        <el-row style="height: 40px">
          <el-input prefix-icon="el-icon-search" style="width:100%" v-model="orgQuery.name" placeholder="关键字"></el-input>
        </el-row>
        <div style="margin-bottom: 20px"></div>
        <el-row>
          <el-tree v-loading="treeLoading" class="dcs-left-tree"  ref="OrganizeTreeRef" :check-strictly="true" :filter-node-method="filterNode" :data="OrganizeTree"
                       :props="treeProps" node-key="id" default-expand-all  show-checkbox :close-on-click-modal="false" @check="treeCheck" @node-click="nodeCheck">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <span v-if="data.type==OrgnizeType.ANCESTOR" class="mgl-10"><span class="tenant-title">{{ data.name }}</span></span>
                <span v-else-if="data.type==OrgnizeType.FACTORY" class="mgl-10"><span class="company-title">{{ data.name }}</span><el-tag v-if="data.sub_title" type="info" size="mini">({{ data.sub_title }})</el-tag></span>
                <span v-else-if="data.type==OrgnizeType.DEPARTENT" class="mgl-10"><span class="department-title">{{ data.name }}</span></span>
              </span>
            </span>
          </el-tree>
        </el-row>
      </el-aside>
      <el-container>
        <el-header class="date-search-header">
          <el-select v-model="orgQuery.module_name" placeholder="请选择模块" @change="moduleChange">
            <el-option v-for="(item, index) in moduleList" :key="index" :label="item.cn_name" :value="item.en_name" />
          </el-select>
        </el-header>
        <el-main v-loading="fieldsLoading">
          <el-empty description="请选择组织" v-if="!orgQuery.orgnization_id"></el-empty>
          <div class="mfields-view"  v-if="orgQuery.orgnization_id">
            <el-empty description="当前模块没有数据" v-if="!tabsData.length"></el-empty>
            <el-tabs v-model="activeGroup" v-if="tabsData.length">
              <el-tab-pane v-for="(item, index) in tabsData" :key="index" :label="item.group_name" :name="item.group_name">
                <el-row class="checkbox-container" :gutter="10" type="flex" justify="start" align="middle">
                  <el-col style="margin-bottom: 10px" :span="6" v-for="(box, idx) in item.list" :key="idx">
                    <el-checkbox v-model="box.checked" :label="box.alias?box.alias:box.cn_name" border size="medium"></el-checkbox>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="fields-bottom" v-if="orgQuery.orgnization_id">
            <el-button style="float: right" type="primary" @click.native="saveModuleConf" v-if="tabsData.length">保存</el-button>
            <el-button style="float: right; margin-right: 20px" type="warning" @click.native="copyModuleConf" v-if="tabsData.length">复制</el-button>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <el-dialog title="复制模块配置" :visible.sync="copyModuleVisible" width="80%" >
      <el-form ref="dataForm" label-position="left" label-width="120px" :model="copyTemp" >
        <el-form-item label="当前模块" prop="module_name">
          <el-select v-model="copyTemp.module_name" style="width: 100%" placeholder="请选择模块" disabled>
            <el-option v-for="(item, index) in moduleList" :key="index" :label="item.cn_name" :value="item.en_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前电厂" prop="curr_org_id">
          <el-select v-model="copyTemp.curr_org_id" style="width: 100%" placeholder="请选择电厂" disabled>
            <el-option v-for="(item, index) in mainOrganizes" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="全选电厂">
          <el-checkbox v-model="checkedAll" @change="toggleCheck">全选</el-checkbox>
        </el-form-item>
        <el-form-item label="需配置电厂" prop="other_org_ids">
          <el-select v-model="copyTemp.other_org_ids" style="width: 100%" multiple placeholder="请选择电厂">
            <el-option v-for="(item, index) in mainOrganizes" :key="index" :label="item.name" :value="item.id" v-if="item.id!==copyTemp.curr_org_id" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyModuleVisible = false">取消</el-button>
        <el-button type="primary" @click.native="copyConfirm">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import moduleApi from '@/api/module'
  import debounce from 'lodash/debounce'
  import { confirm,OrgnizeType } from '@/utils/constants'
  export default {
    name: 'report-module',
    data(){
      return {
        orgQuery:{
          name:null,
          module_name:null,
          orgnization_id:null
        },
        treeLoading:false,
        fieldsLoading:false,
        OrgnizeType,
        OrganizeTree: [],
        mainOrganizes:[],
        treeProps: {
          label: 'name',
          children: 'children'
        },
        moduleList:[],
        tabsData:[],
        activeGroup:'',
        copyModuleVisible:false,
        checkedAll:false,
        copyTemp:{
          curr_org_id:null,
          other_org_ids:[],
          module_name:null
        }
      }
    },
    watch: {
      'orgQuery.name': debounce(function(val) {
        this.$refs.OrganizeTreeRef.filter(val)
      }, 600)
    },
    created() {
      this.fetchData()
    },
    methods:{
      async fetchData() {
        this.treeLoading = true
        this.OrganizeTree = await this.$store.dispatch('user/ownedOrgnizes', 4)
        this.mainOrganizes = this.OrganizeTree[0].children
        this.fetchModuleList()
        this.treeLoading = false
      },
      fetchModuleList(){
        moduleApi.rptModuleList().then(res=>{
          this.moduleList = res.data
          this.orgQuery.module_name = this.moduleList[0].en_name
          this.treeDefaultCheck()
        })
      },
      treeDefaultCheck(){
        const firstNode = this.OrganizeTree[0].children[0]
        this.$nextTick(()=>{
          this.$refs['OrganizeTreeRef'].setChecked(firstNode.id, true, false)
          this.treeCheck(firstNode)
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      moduleChange(val){
        if (!this.orgQuery.orgnization_id){
          this.$message.warning("请选择组织!")
          return
        }
        this.fetchFieldsData()
      },
      treeCheck(row,data){
        const needClosed = this.$refs.OrganizeTreeRef.getCheckedKeys().filter(ck=>ck!=row.id)
        needClosed.forEach(ck=> {
          this.$refs.OrganizeTreeRef.setChecked(ck, false, false)
        })
        const currentOrgIds = this.$refs.OrganizeTreeRef.getCheckedKeys()
        this.orgQuery.orgnization_id = null
        if (currentOrgIds.length)
          this.orgQuery.orgnization_id = currentOrgIds[0]
        if (!this.orgQuery.orgnization_id){
          this.$message.warning("请选择组织!")
          return
        }
        if (!this.orgQuery.module_name){
          this.$message.warning("请选择模块!")
          return
        }
        this.fetchFieldsData()
      },
      nodeCheck(row, node, el){
        this.$refs['OrganizeTreeRef'].setChecked(row.id, true, false)
        this.treeCheck(row)
      },
      fetchFieldsData(){
        this.tabsData=[]
        this.fieldsLoading=true
        moduleApi.rptModuleInputs(this.orgQuery).then(res=>{
          this.tabsData = res.data
          if (this.tabsData.length)
            this.activeGroup = this.tabsData[0].group_name
          this.fieldsLoading=false
        })
      },
      saveModuleConf(){
        if (!this.orgQuery.orgnization_id){
          this.$message.warning("请选择组织!")
          return
        }
        if (!this.orgQuery.module_name){
          this.$message.warning("请选择模块!")
          return
        }
        let allTags = []
        this.tabsData.forEach(tb=> allTags.push(...tb.list))
        const dcs_standard_ids = allTags.filter(tag=>tag.checked).map(tag=>tag.id).join(',')
        let rqData= Object.assign({},this.orgQuery)
        rqData['dcs_standard_ids'] = dcs_standard_ids.length?dcs_standard_ids:''
        this.fieldsLoading=true
        moduleApi.rptModuleStore(rqData).then(res=>{
          this.fieldsLoading=false
          this.$message.success("保存成功")
          this.clearModule()
        }).catch(err=>{
          this.fieldsLoading=false
        })
      },
      copyModuleConf(){
        this.copyTemp.module_name=this.orgQuery.module_name
        this.copyTemp.curr_org_id=this.orgQuery.orgnization_id
        this.copyTemp.other_org_ids=[]
        this.checkedAll=false
        this.copyModuleVisible=true
      },
      copyConfirm(){
        this.$confirm(`您确定要复制当前电厂配置到所选电厂吗？`, '提示', confirm).then(() => {
          let cpData = Object.assign({},this.copyTemp)
          cpData.other_org_ids=cpData.other_org_ids.join(",")
          moduleApi.rptModuleCopy(cpData).then(res=>{
            this.$message.success("复制成功")
            this.copyModuleVisible=false
          })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消复制' })
        })
      },
      clearModule(){
        this.orgQuery.orgnization_id=null
        this.$refs.OrganizeTreeRef.setCheckedKeys([]);
        this.tabsData=[]
      },
      toggleCheck(val){
        if (val){
          this.copyTemp.other_org_ids = this.mainOrganizes.map(org=>org.id).filter(oid=>oid!==this.copyTemp.curr_org_id)
        }else {
          this.copyTemp.other_org_ids=[]
        }
      }

    }

  }
</script>

<style lang="scss" scoped>
  @import 'src/styles/variables.scss';
  .tenant-title{
    font-weight: normal;
    color:$tenant-color;
  }
  .company-title{
    font-weight: lighter;
    color: $company-color;
    font-size: small;
    margin-right: 10px;
  }
  .department-title{
    font-weight: lighter;
    color: $department-color;
    font-size: small;
  }
  .app-container{
    padding: 0;

      .dcs-main-container{
        width: 100%;
        min-height: calc(100vh - 84px);
      }
      .real-aside{
        margin-bottom: 0;
        max-height:calc(100vh - 84px);
        overflow-y: auto;

        .el-tree{
          min-height: calc(100vh - 204px);
          padding-top: 10px;
          width: 100%;
          overflow-x: auto;
          overflow-y: hidden;
        }

        .el-tree>.el-tree-node{
          display: inline-block;
          min-width: 100%;
        }

    }
    .date-search-header{
      padding: 0 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .mfields-view{
      width: 100%;
      height: calc(100% - 50px);
    }
    .checkbox-container{
      width: 100%;
      padding: 10px;
      flex-wrap: wrap;
    }
    .fields-bottom{
      width: 100%;
      height: 50px;
      position: relative;
    }


  }

</style>
